//
//  SEGWebViewController.m
//  SEGWebView_Example
//
//  Created by 山刘 on 2020/3/13.
//  Copyright © 2020 samlau7245@icloud.com. All rights reserved.
//

#import "SEGWebViewController.h"
#import "PayListViewController.h"
#import <NSString+WKAdd.h>
#import "SEGProfileModel.h"
#import <YYModel.h>

@interface SEGWebViewController ()

@end

@implementation SEGWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)getOrderPayResult:(NSNotification*)notification{
    [self loadCbUrlString];
}

#pragma mark - 父类抽象方法
/// JS协议拦截
-(BOOL)jsInvokeSystemFunctionWithWebView:(WKWebView *)webView request:(NSURLRequest *)request query:(nonnull NSString *)query{
    if ([super jsInvokeSystemFunctionWithWebView:webView request:request query:query]) {
        NSString * scheme = request.URL.scheme;
        NSString * host = request.URL.host;
        
        // 基于：window.location.href拦截JS协议，唤起原生方法
        if (scheme && host && [scheme rangeOfString:@"uhomeoc"].location != NSNotFound){
            // 第三方使用api：跳转到支付列表
            if ([request.URL.host rangeOfString:@"thirdparty.goPayList"].location != NSNotFound) {
                PayListViewController *payListVC = [PayListViewController new];
                payListVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:payListVC animated:YES];
                return NO;
            }
            // 第三方使用api：支付
            if ([request.URL.host rangeOfString:@"thirdparty.pay"].location != NSNotFound) {
                NSURL *url = [NSURL URLWithString:@"app2Scheme://"];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                    }];
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];
                    
                }else{
                    NSLog(@"没有安装应用SchemesA");
                }
                return NO;
            }
            if ([request.URL.host rangeOfString:@"userInfo.get"].location != NSNotFound) { // 用户信息-获取用户信息
                NSLog(@"%@",[query toDictionary]);
                NSDictionary *params = [query toDictionary];
                if (!(params && [params isKindOfClass:[NSDictionary class]])) return NO;
                
                NSArray *para = [params valueForKey:@"para"];
                NSString *fn = [params valueForKey:@"fn"];
                
                para = (para && [para isKindOfClass:[NSArray class]])? para: [NSArray array];
                fn = fn ? [NSString toString:fn]: @"";
                
                
                NSDictionary * dic = [[SEGProfileManager sharedManager].profile yy_modelToJSONObject];
                NSMutableDictionary  *tmp = [NSMutableDictionary dictionary];
                [para enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isKindOfClass:[NSString class]]) {
                        if ([[dic allKeys] containsObject:obj]) {
                            [tmp setValue:[dic valueForKey:obj] forKey:obj];
                        }
                    }
                }];
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:@"1" forKey:@"code"];
                [dict setObject:@"" forKey:@"message"];
                [dict setObject:tmp forKey:@"data"];
                NSString *jsString = [NSString stringWithFormat:@"%@(%@)",fn,[dict yy_modelToJSONString]];
                if (jsString && jsString.length > 0){
                    [self.webView evaluateJavaScript:jsString completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                    }];
                }
                return NO;
            }
            if ([request.URL.host rangeOfString:@"system.jumpToNative"].location != NSNotFound) {
                UIViewController *VC = [UIViewController new];
                VC.view.backgroundColor = UIColor.whiteColor;
                [self.navigationController pushViewController:VC animated:YES];
                return NO;
            }
        }
    }
    return YES;
}
/// URL地址参数替换
-(NSString*)segReplaceUrlStringWithUrlString:(NSString *)urlString{
    return [super segReplaceUrlStringWithUrlString:urlString];
}
/// URL地址添加平台号
-(NSString*)getUrlStringWithAppPlatformCode:(NSString *)urlString{
    NSString *app_platform = [NSString stringWithFormat:@"app_platform_code=%@",@"SEGI"];
    NSString *company_platform = [NSString stringWithFormat:@"company_platform_code=%@",@"SEGI"];
    //app_version_code 修改成接口版本号
    NSString *app_version = [NSString stringWithFormat:@"app_version_code=%@",@"1"];
    
    if ([urlString rangeOfString:app_platform].location == NSNotFound) {
        //拼app_platform
        if ([urlString rangeOfString:@"?"].location == NSNotFound) {
            //没有任何参数时 用？拼接
            urlString = [NSString stringWithFormat:@"%@?%@", urlString, app_platform];
        }else {
            urlString = [NSString stringWithFormat:@"%@&%@", urlString, app_platform];
        }
    }
    
    if ([urlString rangeOfString:company_platform].location == NSNotFound) {
        //拼app_platform
        if ([urlString rangeOfString:@"?"].location == NSNotFound) {
            //没有任何参数时 用？拼接
            urlString = [NSString stringWithFormat:@"%@?%@", urlString, company_platform];
        }else {
            urlString = [NSString stringWithFormat:@"%@&%@", urlString, company_platform];
        }
    }
    
    if ([urlString rangeOfString:app_version].location == NSNotFound) {
        //拼app_version3
        if ([urlString rangeOfString:@"?"].location == NSNotFound) {
            //没有任何参数时 用？拼接
            urlString = [NSString stringWithFormat:@"%@?%@", urlString, app_version];
        }else {
            urlString = [NSString stringWithFormat:@"%@&%@", urlString, app_version];
        }
    }
    return urlString;
}

-(void)segShare:(NSString*)query{
    NSLog(@"\n%@\n%@",query,self.currentUrl.absoluteString);
}

-(BOOL)isShowProgressView{
    return YES;
}
@end
